<template>
  <div>
    <el-card shadow="always">
      <CategorySelect @getAttrList="getAttrList" :show="isShowTable"/>
    </el-card>
    <el-card shadow="hover" style="margin: 20px 0px;">
      <!--      两个div块具有排他性-->
      <!--      添加按钮和属性表格div块-->
      <div v-show="isShowTable">
        <!--      添加按钮-->
        <el-button type="primary"
                   icon="el-icon-plus"
                   style="margin:0px 0px 20px 0px"
                   :disabled="!IdForm.Category3Id"
                   @click="addAttr"
        >添加属性
        </el-button>
        <!--      table表格-->
        <el-table border style="width: 100%" :data="AttrList">
          <el-table-column label="序号" type="index" width="80px" align="center"></el-table-column>
          <el-table-column label="属性名称" prop="attrName" width="150px"></el-table-column>
          <el-table-column label="属性值列表" prop="prop" width="width">
            <template slot-scope="{row,$index}">
              <el-tag type="success" v-for="(attr,index) in row.attrValueList" :key="attr.id" style="margin: 0px 10px">
                {{ attr.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220px">
            <template slot-scope="{row,$index}">
              <el-button type="warning" icon="el-icon-edit" @click="editAttrValue(row)">编辑</el-button>
              <el-button type="danger" icon="el-icon-delete" @click="deleteAttrInfo(row)">删除</el-button>
            </template>
          </el-table-column>
<!--          分页器-->


        </el-table>
      </div>
      <!--      属性添加块 表单+表格div块-->
      <div v-show="!isShowTable">
        <el-form :inline="true" class="demo-form-inline" v-model="newAttrInfo">
          <el-form-item label="属性名" style="margin:0px 0px 20px 0px">
            <el-input placeholder="请输入" v-model="newAttrInfo.attrName"></el-input>
          </el-form-item>
        </el-form>
        <el-button type="primary"
                   icon="el-icon-plus"
                   style="margin:0px 10px 20px 0px"
                   :disabled="!newAttrInfo.attrName"
                   @click="addAttrValue"
        >添加属性值</el-button>
        <el-button @click="isShowTable=true" style="margin:0px 0px 20px 0px">取消</el-button>

        <el-table border style="width: 100%;margin:0px 0px 20px 0px" :data="newAttrInfo.attrValueList">
          <el-table-column label="序号" type="index" width="150px" align="center"></el-table-column>
          <el-table-column label="属性名" prop="valueName" width="width">
            <template slot-scope="{row,$index}">
              <el-input v-if="row.flag"
                        @blur="toLook(row)"
                        @keyup.enter.native="toLook(row)"
                        :ref="$index"
                        placeholder="请输入属性值"
                        v-model="row.valueName"
                        size="mini"></el-input>
              <span v-else @click="toEdit(row,$index)" style="display:block">{{row.valueName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="width">
            <template slot-scope="{row,$index}">
              <el-popconfirm :title="`确定删除${row.valueName}吗？`" @onConfirm="deleteAttrValue($index)" >
                <el-button slot="reference" type="danger" icon="el-icon-delete">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="saveAttrInfo" :disabled="newAttrInfo.attrValueList.length<1">保存</el-button>
        <el-button @click="isShowTable=true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
//引入深拷贝
import cloneDeep from 'lodash/cloneDeep'

export default {
  name: 'Attr',
  data() {
    return {
      //三级分类id
      IdForm: {
        Category1Id: "",
        Category2Id: "",
        Category3Id: "",
      },
      //属性列表
      AttrList: [],
      //属性列表table是否展示
      isShowTable: true,
      //新增的属性值
      newAttrInfo: {
        attrName: "",//属性名
        attrValueList: [],//属性值有多个，每个属性值都有对应的attrId和valueName
        categoryId: 0,//三级分类的id
        categoryLevel: 3,//后台需要接收到该分类id的级别，3级id
      }
    }
  },
  methods: {
    async getAttrList(IdForm) {
      this.IdForm = IdForm;
      // console.log('发请求！');
      //解构IdForm
      const {Category1Id, Category2Id, Category3Id} = this.IdForm;
      const result = await this.$API.default.attr.reqAttrList(Category1Id, Category2Id, Category3Id)
      // console.log(result)
      if (result.code == 200) {
        this.AttrList = result.data;
      }
    },
    //添加属性值
    addAttrValue(){
      this.newAttrInfo.attrValueList.push({
        attrId: this.newAttrInfo.id,
        valueName: "",
        flag:true,//控制新加属性的查看和编辑状态
      })
      this.$nextTick(()=>{
        this.$refs[this.newAttrInfo.attrValueList.length-1].focus();
      })
    },
    //添加属性按钮的点击事件，目的：1、绑定Categort3Id,2、清除前一次的添加残留数据，重新开始新的添加
    addAttr(){
      this.isShowTable=false
      this.newAttrInfo= {
        attrName: "",//属性名
        attrValueList: [],//属性值有多个，每个属性值都有对应的attrId和valueName
        categoryId: 0,//三级分类的id
        categoryLevel: 3,//后台需要接收到该分类id的级别，3级id
      }
      this.newAttrInfo.categoryId=this.IdForm.Category3Id;
    },
    //修改属性值
    editAttrValue(row){
      this.isShowTable=false,
      // console.log("row",row);
      this.newAttrInfo=cloneDeep(row)
      this.newAttrInfo.attrValueList.forEach(item=>{
        //三个参数，第一个：添加参数的对象或者数组，第二个：添加的属性字段名，可以为字符串或者数字，第三个：新增参数的初始值。
        this.$set(item,"flag",false);
      })
    },
    //处理查看状态
    toLook(row){
      if(row.valueName.trim()===''){
        this.$message({
          message:'输入不能为空',
          type:'warning'
        })
        return;
      }
      let isRepeat =  this.newAttrInfo.attrValueList.some(item=>{
        if(row!=item){
          return row.valueName==item.valueName;
        }
      })
      // console.log(isRepeat)
      if(isRepeat){
        this.$message({
          message:'不能输入重复值',
          type:'warning'
        })
        return;
      }
      row.flag=false
    },
    //处理编辑状态
    toEdit(row,index){
      row.flag=true
      this.$nextTick(()=>{
        this.$refs[index].focus();
      })
    },
    //删除属性添加表中的属性值
    deleteAttrValue(index){
      this.newAttrInfo.attrValueList.splice(index,1);
    },
    //保存attrInfo，保存到后端数据库
    async saveAttrInfo() {
      //处理attrInfo，去除flag字段，去除重复数据
      this.newAttrInfo.attrValueList = this.newAttrInfo.attrValueList.filter((item) => {
        if (item.valueName != '') {
          delete item.flag;
          return true;
        }
      })
      //发送保存请求
      try {
        const result = await this.$API.default.attr.reqSaveAttr(this.newAttrInfo);
        // console.log("newAttrInfo", result);
        if (result.code == 200) {
          //保存成功
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.isShowTable = true;
          //发请求，更新table数据
          this.getAttrList(this.IdForm);
        }
      } catch (error) {
        this.$message({
          message: error.message,
          type: 'error'
        })
      }
    },
    //删除属性值，后端删除属性值
    deleteAttrInfo(row) {
      this.$confirm(`此操作将永久删除${row.attrName}属性, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        console.log("deleteAttrInfo");
        this.newAttrInfo = cloneDeep(row);
        //删除属性值列表
        this.newAttrInfo.attrValueList = [];
        // 发送保存请求
        try {
          const result = await this.$API.default.attr.reqSaveAttr(this.newAttrInfo);
          console.log("deleteAttrInfo", result);
          if (result.code == 200) {
            //发请求，更新table数据
            this.getAttrList(this.IdForm);
            //保存成功
            this.$message({
              message: '删除成功',
              type: 'success'
            })
          }
        } catch (error) {
          this.$message({
            message: error.message,
            type: 'error'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
}
</script>

<style scoped>

</style>
